package com.thyme.web.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author ah.caixiaodong@aisino.com
 * @ClassName TimeInterceptor
 * @Description TODO
 * @Date 2019/6/5 11:46
 */
@Component
public class TimeInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(TimeInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
        logger.info("preHandle");
        logger.info(((HandlerMethod)object).getBean().getClass().getName());
        logger.info(((HandlerMethod)object).getMethod().getName());
        request.setAttribute("startTime",System.currentTimeMillis());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object, ModelAndView modelAndView) throws Exception {
        logger.info("postHandle");
        Long start = (Long)request.getAttribute("startTime");
        logger.info("time interceptor 耗时：" + (System.currentTimeMillis()-start));
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object object, Exception e) throws Exception {
        logger.info("afterCompletion");
        Long start = (Long)request.getAttribute("startTime");
        logger.info("time interceptor 耗时：" + (System.currentTimeMillis()-start));
        logger.info("ex is " + e);
    }
}
